package cn.itcast.music.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import cn.itcast.music.R;
import cn.itcast.music.entity.Music;
import cn.itcast.music.entity.MusicHistory;
import cn.itcast.music.util.DateTimeUtil;
import cn.itcast.music.util.MusicUtil;
import java.io.IOException;
import java.util.List;

public class MusicPlayingService extends Service {

    private static final String LOG_TAG = "App-MusicPlayerService";

    private MediaPlayer player;

    private List<Music> musicList;

    private int position;

    @Override
    public void onCreate() {
        startForeground();
        Log.d(LOG_TAG, "音乐播放服务创建成功！");
    }

    private void startForeground() {
        Log.d(LOG_TAG, "启动前台服务");
        String channelId;
        if (VERSION.SDK_INT >= VERSION_CODES.O) {
            channelId = createNotificationChannel();
        } else {
            channelId = "";
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this, channelId);
        Notification notification = builder.setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(false)
                .setOngoing(true)
                .setShowWhen(false)
                .setSilent(true)
                .setContentTitle("音乐播放器")
                .setContentText("聆听你的美~")
                .build();
        startForeground(1, notification);
    }

    private String createNotificationChannel() {
        NotificationChannel channel;
        if (VERSION.SDK_INT >= VERSION_CODES.O) {
            channel = new NotificationChannel("cn.itcast.music",
                    "MusicPlayerService", NotificationManager.IMPORTANCE_HIGH);
            NotificationManager manager = getSystemService(
                    NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
        return "cn.itcast.music";
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        musicList = MusicUtil.getReadonlyMusicList();
        position = intent.getIntExtra("position", 0);

        Log.d(LOG_TAG, "服务绑定成功！");
        Log.d(LOG_TAG, "musicList=" + musicList);
        Log.d(LOG_TAG, "position=" + position);
        return new MusicPlayingBinder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
        stopForeground(STOP_FOREGROUND_REMOVE);
    }

    public void playOrPause() {
        if (checkMusicListValid()) {
            operatePlayerAutoInit(() -> {
                if (isPlaying()) {
                    Log.d(LOG_TAG, "暂停播放");
                    player.pause();
                } else {
                    Log.d(LOG_TAG, "开始/继续播放");
                    player.start();
                    if (MusicUtil.latestMusicHistory().getMusic()
                            != currentMusic()) {
                        MusicUtil.addMusicHistory(getApplicationContext(),
                                new MusicHistory(
                                        DateTimeUtil.formattedDateTimeNow(),
                                        currentMusic()));
                    }
                }
            });
        }
    }

    public void seekTo(int progress) {
        if (checkMusicListValid()) {
            operatePlayerAutoInit(() -> {
                Log.d(LOG_TAG, "跳转到：" + progress);
                player.seekTo(progress);
            });
        }
    }

    private void operatePlayerAutoInit(Runnable operation) {
        if (player != null) {
            operation.run();
        } else if (initPlayerSuccess()) {
            operation.run();
        }
    }

    public void play(int position) {
        if (checkMusicListValid()) {
            if (isPlaying(position)) {
                Log.d(LOG_TAG, "本音乐已在播放");
            } else {
                this.position = position;
                operatePlayerAutoReset(() -> {
                    Log.d(LOG_TAG, "开始播放：" + musicList.get(position));
                    player.start();
                    MusicUtil.addMusicHistory(getApplicationContext(),
                            new MusicHistory(
                                    DateTimeUtil.formattedDateTimeNow(),
                                    musicList.get(position)));
                });
            }
        }
    }

    public void playLast() {
        if (checkMusicListValid()) {
            if (position == 0) {
                position = musicList.size() - 1;
            } else {
                position--;
            }
            operatePlayerAutoReset(() -> {
                Log.d(LOG_TAG, "播放上一首：" + musicList.get(position));
                player.start();
                MusicUtil.addMusicHistory(getApplicationContext(),
                        new MusicHistory(DateTimeUtil.formattedDateTimeNow(),
                                musicList.get(position)));
            });
        }
    }

    public void playNext() {
        if (checkMusicListValid()) {
            if (position == musicList.size() - 1) {
                position = 0;
            } else {
                position++;
            }
            operatePlayerAutoReset(() -> {
                Log.d(LOG_TAG, "播放下一首：" + musicList.get(position));
                player.start();
                MusicUtil.addMusicHistory(getApplicationContext(),
                        new MusicHistory(DateTimeUtil.formattedDateTimeNow(),
                                musicList.get(position)));
            });
        }
    }

    private void operatePlayerAutoReset(Runnable operation) {
        if (player != null && resetPlayerSuccess()) {
            operation.run();
        } else if (initPlayerSuccess()) {
            operation.run();
        }
    }

    public boolean isPlaying(int position) {
        return this.position == position && isPlaying();
    }

    public boolean isPlaying() {
        return player != null && player.isPlaying();
    }

    public int currentProgress() {
        return player != null ? player.getCurrentPosition() : 0;
    }

    public Music currentMusic() {
        return musicList.get(position);
    }

    private boolean checkMusicListValid() {
        if (musicList == null || musicList.size() <= position) {
            Toast.makeText(this, "音乐列表为空！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private boolean initPlayerSuccess() {
        player = new MediaPlayer();
        player.setOnCompletionListener(mediaPlayer -> playNext());
        try {
            player.setDataSource(musicList.get(position).getPath());
            player.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "设置数据源失败", e);
            return false;
        }
        return true;
    }

    private boolean resetPlayerSuccess() {
        player.reset();
        try {
            player.setDataSource(musicList.get(position).getPath());
            player.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "设置数据源失败", e);
            return false;
        }
        return true;
    }

    public void addMusicListToMenu(Menu menu) {
        for (int i = 0; i < musicList.size(); i++) {
            menu.add(Menu.NONE, i, Menu.NONE, musicList.get(i).getTitle());
        }
    }

    public class MusicPlayingBinder extends Binder {

        public MusicPlayingService getService() {
            return MusicPlayingService.this;
        }

    }

}
